package com.mall;

import com.mall.auth.AuthAccessDeniedHandler;
import com.mall.auth.AuthFailureHandler;
import com.mall.auth.AuthSuccessHandler;
import com.mall.auth.UserSecurityServiceImpl;
import com.mall.utils.SysPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class ShopWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
	
	   @Autowired
	   private UserSecurityServiceImpl userDetailsService;
	
	
	
   @Override
   protected void configure(AuthenticationManagerBuilder auth) throws Exception {
	   DaoAuthenticationProvider daoAuth = new DaoAuthenticationProvider();
	   daoAuth.setHideUserNotFoundExceptions(true);// 返回错误信息提示，而不是Bad Credential
	      daoAuth.setUserDetailsService(userDetailsService); // 覆盖UserDetailsService类
	      daoAuth.setPasswordEncoder(new SysPasswordEncoder()); // 覆盖默认的密码验证类
	      auth.authenticationProvider(daoAuth);
   }
   
   
   @Override
   protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests()//
            .antMatchers("/css/**").permitAll()
//             设置 ADMIN/ROLE 访问权限
//      		.antMatchers(("/**")).permitAll()
      		.antMatchers("/images/**","/failure").permitAll()
            .antMatchers("/").hasRole("ADMIN")//
            .antMatchers("/list/**").hasRole("ADMIN")//
            .antMatchers("/test/**").hasRole("ROLE")//
//             用户访问其它的 URL 都必须认证后才能访问（登录后才能访问）
//            .anyRequest().authenticated()//
//             开启表单登录，允许登录所有权限
            .and().formLogin()//
            .loginPage("/login")//
            .loginProcessingUrl("/login")//
//            .failureUrl("/login?error=true")//
            
            .failureHandler(new AuthFailureHandler())//
            .successHandler(new AuthSuccessHandler())//

            .permitAll()//
            .and().exceptionHandling().accessDeniedPage("/login?error=true")//权限不足去哪里
            
            .and().exceptionHandling().accessDeniedHandler(new AuthAccessDeniedHandler())//
      		
            .and().logout().permitAll()//
            
            
            ;
      
   }
}